﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Web.Security;
using System.Data;
using System.Data.SqlClient;
using Xceed.Wpf.Toolkit;
using System.Text.RegularExpressions;

namespace ProjectEF6
{
    /// <summary>
    /// Interaction logic for PanelA.xaml
    /// </summary>
    public partial class PanelA : Window
    {
        DB db = new DB();

        public PanelA()
        {
            InitializeComponent();
            tabBedrijven.DataContext = db.getAllCompanies();
            calendarReservations.SelectedDate = DateTime.Today;
            tabContracten.DataContext = db.getAllContracts();
            tabRunningContracts.DataContext = db.getRunningContracts();

            datepickerStart.Value = DateTime.Now;

            // Combobox voor bedrijf
            List<Company> companies = new List<Company>();
            companies = db.getAllCompanies();
            foreach (Company c in companies)
            {
                cmbCompany.Items.Add(c);
            }
            cmbCompany.SelectedIndex = 0;

            // Combobox voor contractformulas
            List<ContractFormula> contractFormulas = new List<ContractFormula>();
            contractFormulas = db.getAllContractFormulas();
            foreach (ContractFormula c in contractFormulas)
            {
                cmbContractFormula.Items.Add(c);
            }
            cmbContractFormula.SelectedIndex = 0;
        }

        private void btnAddCompany_Click(object sender, RoutedEventArgs e)
        {
            String tel = txtTelephone.Text.Replace(" ", String.Empty);
            String empl = txtEmployees.Text.Replace(" ", String.Empty);
            if (checkTextfields(txtName.Text, txtStreet.Text, txtZipcode.Text, txtCity.Text, txtCountry.Text, txtEmail.Text, txtTelephone.Text, txtEmployees.Text) & checkEmail(txtEmail.Text) & IsAllDigits(tel) & IsAllDigits(empl))
            {
                int phone = Convert.ToInt32(tel);
                int employees = Convert.ToInt32(empl);
                db.newCompany(txtName.Text, txtStreet.Text, Convert.ToInt32(txtZipcode.Text), txtCity.Text, txtCountry.Text, txtEmail.Text, phone, employees);
                tabBedrijven.DataContext = db.getAllCompanies();
            }
        }

        public Boolean checkTextfields(String t1,String t2,String t3,String t4,String t5,String t6,String t7,String t8)
        {

            if (string.IsNullOrWhiteSpace(t1) || string.IsNullOrWhiteSpace(t2) || string.IsNullOrWhiteSpace(t3) || string.IsNullOrWhiteSpace(t4) || string.IsNullOrWhiteSpace(t5) || string.IsNullOrWhiteSpace(t6) || string.IsNullOrWhiteSpace(t7) || string.IsNullOrWhiteSpace(t8))
            {
                System.Windows.MessageBox.Show("Niet alle velden zijn ingevuld!");
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool IsAllDigits(string s)
        {
            foreach (char c in s)
            {
                if (!Char.IsDigit(c))
                {
                    Console.WriteLine("Is geen nummer!!");
                    return false;
                }
            }
            return true;
        }

        public Boolean checkEmail(String email)
        {
            if (!Regex.IsMatch(email, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
            {
                System.Windows.MessageBox.Show("Geef een juiste E-mail in!");
                //Console.WriteLine("Geef een juiste E-mail in!");
                return false;
            }
            else
            {
                return true;
            }
        }

        private void btnEditBedrijf_Click(object sender, RoutedEventArgs e)
        {
            Company c = (Company)listboxBedrijven.SelectedItem;
            int index = listboxBedrijven.SelectedIndex;
            EditCompany edit = new EditCompany(c.Id, c.Name, c.Street, c.Zipcode, c.City, c.Country, c.Email, c.Phone, c.Employees);
            edit.ShowDialog();
            // Reserveringen updaten
            tabBedrijven.DataContext = db.getAllCompanies();
            // Reserveringen selectie zetten op de item de bewerkt is.
            listboxBedrijven.SelectedIndex = index;
        }

        private void btnDeleteBedrijf_Click(object sender, RoutedEventArgs e)
        {
            Company c = (Company)listboxBedrijven.SelectedItem;
            if (db.checkIfContractCompany(c.Id))
            {
                if (System.Windows.MessageBox.Show("Bent u zeker dat u bedrijf met id " + c.Id + " wilt verwijderen?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                {
                    db.deleteCompany(c.Id);
                    tabBedrijven.DataContext = db.getAllCompanies();
                }
            }
        }

        private void calendarReservations_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            DateTime startSelected = (DateTime)calendarReservations.SelectedDate.Value;
            DateTime endSelected = (DateTime)startSelected.AddDays(1);

            List<reservations> r = new List<reservations>();
            r = db.getReservationsFromDay(startSelected, endSelected);

            tabReservaties.DataContext = r;
        }

        private void btnAddContract_Click(object sender, RoutedEventArgs e)
        {
            
            ContractFormula c = (ContractFormula)cmbContractFormula.SelectedItem;
            Company comp = (Company)cmbCompany.SelectedItem;

            DateTime start = (DateTime)datepickerStart.Value;
            int months = c.PeriodInMonths;
            DateTime end = start.AddMonths(months);
            int companyId = comp.Id;
            int formulaId = c.Id;
            if (checkContractDates(start,end,companyId))
            {
                //System.Windows.MessageBox.Show("Insert: " + start + " " + end + " " + companyId + " " + formulaId);
                db.newContract(start, end, companyId, formulaId);
                tabContracten.DataContext = db.getAllContracts();
            }
            //Location l = (Location)cmbLocation.SelectedItem;
            //Company c = (Company)cmbCompany.SelectedItem;

            //if (checkDates(start, end, l.Id) == true && checkContract(start, end, c.Id) == true)
            //{
            //    db.newReservation(l.Id, start, end, c.Id);
            //    tabReservaties.DataContext = db.getAllReservations();
            //}
        }

        public Boolean checkContractDates(DateTime start, DateTime end, int companyId)
        {
            Boolean status = true; // true = insert mag gebeuren / false = insert mag niet gebeuren
            if (start == null || end == null)
            {
                System.Windows.MessageBox.Show("Vul een datum en tijd in.");
                status = false;
            }

            if (start >= end)
            {
                System.Windows.MessageBox.Show("De begindatum kan niet na de einddatum liggen.");
                status = false;
            }

            if (start <= DateTime.Now)
            {
                System.Windows.MessageBox.Show("De begindatum kan niet in het verleden liggen.");
                status = false;
            }

            List<Contract> contracten = new List<Contract>();
            contracten = db.getContractsCompany(companyId);
            Boolean b = false; // boolean voor overlapContract() method, true = messagebox met warning / false = geen warning
            foreach (Contract r in contracten)
            {
                if (start <= r.StartDate && end <= r.EndDate && end >= r.StartDate)
                {
                    b = true;
                    status = false;
                }
                if (start <= r.StartDate && end >= r.EndDate)
                {
                    b = true;
                    status = false;
                }
                if (start >= r.StartDate && end <= r.EndDate)
                {
                    b = true;
                    status = false;
                }
                if (start >= r.StartDate && start <= r.EndDate && end >= r.EndDate)
                {
                    b = true;
                    status = false;
                }
            }
            OverlapContract(b);
            return status;
        }

        private void OverlapContract(Boolean b)
        {
            if (b == true)
            {
                System.Windows.MessageBox.Show("De ingegeven datum mag niet overlappen met een bestaand contract.");
            }
        }

        private void btnStopContract_Click(object sender, RoutedEventArgs e)
        {
            Contract c = (Contract)listboxContracten.SelectedItem;
            if (db.checkIfReservationContract(c.Id))
            {
                if (System.Windows.MessageBox.Show("Bent u zeker dat u contract met id " + c.Id + " wilt stop zetten?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                {
                    db.deleteContract(c.Id);
                    tabContracten.DataContext = db.getAllContracts();
                    tabRunningContracts.DataContext = db.getRunningContracts();
                }
            }
        }

        private void btnStopLopendContract_Click(object sender, RoutedEventArgs e)
        {
            Contract c = (Contract)listboxContracts.SelectedItem;
            if(db.checkIfReservationContract(c.Id))
            {
                if (System.Windows.MessageBox.Show("Bent u zeker dat u contract met id " + c.Id + " wilt stop zetten?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                {
                    db.deleteContract(c.Id);
                    tabContracten.DataContext = db.getAllContracts();
                    tabRunningContracts.DataContext = db.getRunningContracts();
                }
            }

        }
    }
}
